<?php
/**
 * Created by PhpStorm.
 * User: CPR065
 * Date: 2016/8/9
 * Time: 10:56
 */

namespace Admin\Event;


class BuildEvent
{
    public $tplPath = null;
    public $controPath = null;

    public function __construct()
    {
        $this->tplPath = APP_PATH . MODULE_NAME . DIRECTORY_SEPARATOR . 'TPL' . DIRECTORY_SEPARATOR;
    }

    public function buildController($data)
    {

        $module = ucfirst($data['module']);
        $controller = ucfirst($data['controller']);
        $model = ucfirst($data['model']);
        $description = $data['description'];
        $replaceRule = [
            '[MODULE]' => $module,
            '[CONTROLLER]' => $controller,
            '[MODEL]' => $model,
            '[DESCRIPTION]' => $description,
        ];
        $file = $this->tplPath . 'Controller.tpl';
        if (file_exists($file)) {
            $content = file_get_contents($file);
            foreach ($replaceRule as $k => $v) {
                $content = str_replace($k, $v, $content);
            }
            while (stripos($content, '[UUID]')) { //替换uuid
                $content = preg_replace('/\[UUID\]/', getRandString(11, 'num'), $content, 1);
            }
            $targetFile = APP_PATH . $module . DIRECTORY_SEPARATOR . 'Controller' . DIRECTORY_SEPARATOR . $controller . 'Controller.class.php';
            if (file_exists($targetFile)) {
                return ['status' => 0, 'info' => '目标文件已经存在!'];
            }
            if (file_put_contents($targetFile, $content)) {
                return ['status' => 1, 'info' => '创建成功!'];
            } else {
                return ['status' => 0, 'info' => '写入失败!'];
            }
        } else {
            return ['status' => 0, 'info' => '模板不存在!'];
        }

    }

    public function buildModel($data)
    {

        $module = ucfirst($data['module']);
        $model = ucfirst($data['model']);
        $table = $data['table'];
        $replaceRule = [
            '[MODULE]' => $module,
            '[TABLE]' => $table,
            '[MODEL]' => $model,
        ];
        $file = $this->tplPath . 'Model.tpl';
        if (file_exists($file)) {
            $content = file_get_contents($file);
            foreach ($replaceRule as $k => $v) {
                $content = str_replace($k, $v, $content);
            }

            $targetFile = APP_PATH . $module . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR . $model . 'Model.class.php';
            if (file_exists($targetFile)) {
                return ['status' => 0, 'info' => '目标文件已经存在!'];
            }
            if (file_put_contents($targetFile, $content)) {
                return ['status' => 1, 'info' => '创建成功!'];
            } else {
                return ['status' => 0, 'info' => '写入失败!'];
            }
        } else {
            return ['status' => 0, 'info' => '模板不存在!'];
        }

    }

    public function buildView($data)
    {

        $module = ucfirst($data['module']);
        $controller = ucfirst($data['controller']);
        $table = $data['table'];
        $tplArr = [
            'TITLE' => '<th>%s</th>' . "\n\t\t\t\t\t\t\t",
            'ELEMENT' => '<td>{$vo.%s}</td>' . "\n\t\t\t\t\t\t\t\t",
            'INPUT' => '<div class="form-group">
                            <label class="col-sm-2 control-label">[COMMENT] (required)</label>
                            <div class="col-sm-10">
                                <input class="form-control"  name="[FIELD]"  type="text"  value="{$info.[FIELD]}" placeholder="[COMMENT]"/>
                            </div>
                        </div>'."\n\t\t\t\t\t\t\t\t",
            'RULES' => '
                        [FIELD]: "required",',
            'MESSAGES' => '
                        [FIELD]: "[TITLE]必填",'
        ];

        //创建目录
        $filePath = APP_PATH . $module . DIRECTORY_SEPARATOR . 'View' . DIRECTORY_SEPARATOR . C('DEFAULT_THEME') . DIRECTORY_SEPARATOR . $controller;
        if (file_exists($filePath)) {
            return ['status' => 0, 'info' => $filePath . '目录已经存在!'];
        }
        if (!mkdir($filePath)) {
            return ['status' => 0, 'info' => $filePath . '创建目录失败'];
        }
        $sql = 'show full fields from ' . C('DB_PREFIX') . $table;
        $tableInfo = M()->query($sql);
        $editFile = $this->tplPath . 'edit.tpl';
        $listFile = $this->tplPath . 'list.tpl';
        $fileArr = [$listFile, $editFile];
        //不用显示的字段
        $disableFile = ['create_time', 'update_time', 'id', 'status'];
        foreach ($fileArr as $k => $file) {
            if (file_exists($file)) {
                $content = file_get_contents($file);
                //替换规则
//                foreach($replaceRule as $k=>$v){
//                    $content = str_replace($k,$v,$content);
//                }
                //替换字段
                $titleStr = $elementStr = $inputStr = $rulesStr = $messagesStr = '';
                foreach ($tableInfo as $k => $v) {
                    if (!in_array($v['field'], $disableFile)) {

                        $titleStr .= sprintf($tplArr['TITLE'], $v['comment']);
                        $elementStr .= sprintf($tplArr['ELEMENT'], $v['field']);
                        $inputStr .= str_replace(['[COMMENT]', '[FIELD]'], [$v['comment'], $v['field']], $tplArr['INPUT']);
                        $rulesStr .= str_replace(['[TITLE]', '[FIELD]'], [$v['comment'], $v['field']], $tplArr['RULES']);
                        $messagesStr .= str_replace(['[TITLE]', '[FIELD]'], [$v['comment'], $v['field']], $tplArr['MESSAGES']);
                    }
                }
                //去除json中的最后一个多余的‘,’
                $rulesStr = substr($rulesStr, 0, -1);
                $messagesStr = substr($messagesStr, 0, -1);
                $content = str_replace(['[TITLE]', '[ELEMENT]', '[INPUT]', '[RULES]', '[MESSAGES]'], [$titleStr, $elementStr, $inputStr, $rulesStr, $messagesStr], $content);
                if (stripos($file, 'edit.tpl')) {
                    $tpl = 'edit.html';
                } elseif (stripos($file, 'list.tpl')) {
                    $tpl = 'lis.html';
                }
                $targetFile = APP_PATH . $module . DIRECTORY_SEPARATOR . 'View' . DIRECTORY_SEPARATOR . C('DEFAULT_THEME') . DIRECTORY_SEPARATOR . $controller . DIRECTORY_SEPARATOR . $tpl;
                if (file_exists($targetFile)) {
                    return ['status' => 0, 'info' => $tpl . '目标文件已经存在!'];
                }
                if (file_put_contents($targetFile, $content)) {

                } else {
                    return ['status' => 0, 'info' => '写入失败!'];
                }
            } else {
                return ['status' => 0, 'info' => $file . '模板不存在!'];
            }

        }
        return ['status' => 1, 'info' => '模板生成完毕!'];

    }
} 